package com.zhentao.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhentao.admin.dto.StudentAddDto;
import com.zhentao.admin.dto.StudentSelDto;
import com.zhentao.admin.dto.UpdatePasswordDto;
import com.zhentao.admin.dto.UserJinYongDto;
import com.zhentao.admin.vo.StudentVo;
import com.zhentao.domain.SClass;
import com.zhentao.domain.SMarketingdepartment;
import com.zhentao.domain.TUser;
import com.zhentao.domain.TUserRole;
import com.zhentao.domain.dto.AdTeacher;
import com.zhentao.domain.dto.TeacherDto;
import com.zhentao.domain.dto.UpTeacher;
import com.zhentao.domain.excel.TeacherExport;
import com.zhentao.domain.vo.TuserVO;
import com.zhentao.loginUser.pojo.TRole;
import com.zhentao.mapper.*;
import com.zhentao.result.Result;
import com.zhentao.service.TUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
* @author 86150
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2024-07-22 15:05:16
*/
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService{
    @Resource
    private SMarketingdepartmentMapper sMarketingdepartmentMapper;
    @Resource
    private TUserMapper tUserMapper;
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private TUserRoleMapper tUserRoleMapper;
    @Resource
    private SClassMapper sClassMapper;

    @Resource
    private TRoleMapper roleMapper;
    //获取教师列表
    @Override
    public Result getTeacherList(TeacherDto teacherDto) {
        //分页
        Page<TUser> page=new Page<>(teacherDto.getPageNum(),teacherDto.getPageSize());
        Page<TUser> list=tUserMapper.getTeacherList(page,teacherDto);
        return Result.OK(list);
    }

    @Override
    public PageInfo<StudentVo> selectStudentLimit(StudentSelDto studentSelDto) {
        PageHelper.startPage(studentSelDto.getPageNum(), studentSelDto.getPageSize());
        PageInfo<StudentVo> pageInfo = new PageInfo<>(tUserMapper.selectListStudent(studentSelDto));
        return pageInfo;
    }

    public Result findOneLoginUser(Integer uid){
        TuserVO oneLoginUser = adminMapper.findOneLoginUser(uid);
        TRole tRole = roleMapper.selectOne(Wrappers.<TRole>lambdaQuery().eq(TRole::getRoleName, oneLoginUser.getRoleName()));
        oneLoginUser.setRoles(tRole);
        //返回用户权限字符
        return Result.OK(oneLoginUser);
    }

    @Override
    public Result updateLoginPassword(UpdatePasswordDto updatePasswordDto) {
        TUser byId = this.getById(updatePasswordDto.getUid());
        if (updatePasswordDto.getOldPassword() == null|| updatePasswordDto.getOldPassword().equals("")|| updatePasswordDto.getPassword()==null || updatePasswordDto.getPassword().equals("")) {
            return Result.ERROR("请填写完整原密码和新密码");
        }
        if (!BCrypt.checkpw(updatePasswordDto.getOldPassword(),byId.getPassword())) {
            return Result.ERROR("原密码有误");
        }
        String hashpw = BCrypt.hashpw(updatePasswordDto.getPassword());
        adminMapper.updateLoginPassword(updatePasswordDto.getUid(),hashpw);
        return Result.OK();
    }


    //添加教师
    @Override
    public Result addTeacher(AdTeacher adTeacher) {
        QueryWrapper<TUser> queryWrapper=new QueryWrapper<>();
        //判断该讲师是否已存在
        queryWrapper.eq("username",adTeacher.getUsername());
        if(tUserMapper.selectOne(queryWrapper)!=null){
            return Result.ERROR("账号已存在");
        }
        queryWrapper.eq("nickname",adTeacher.getNickname());
        if(tUserMapper.selectOne(queryWrapper)!=null){
            return Result.ERROR("昵称已存在");
        }
        TUser tUser = new TUser();
        if (adTeacher.getUsername()!=null){
            tUser.setUsername(adTeacher.getUsername());
        }
        if (adTeacher.getPassword()!=null){
            String hashpw = BCrypt.hashpw(adTeacher.getPassword());
            tUser.setPassword(hashpw);
        }
        if (adTeacher.getNickname()!=null){
            tUser.setNickname(adTeacher.getNickname());
        }
        if (adTeacher.getPhone()!=null){
            tUser.setPhone(adTeacher.getPhone());
        }
        if (adTeacher.getAvatar()!=null){
            tUser.setAvatar(adTeacher.getAvatar());
        }
        if (adTeacher.getSex()!=null){
            tUser.setSex(adTeacher.getSex());
        }
        if (adTeacher.getEmail()!=null){
            tUser.setEmail(adTeacher.getEmail());
        }
        //执行新增语句
        int insert = this.tUserMapper.insert(tUser);
        //新增用户和角色的中间表，声明该用户是一个讲师
        TUserRole tUserRole = new TUserRole();
        tUserRole.setUId(tUser.getUserId());
        tUserRole.setRId(2);
        this.tUserRoleMapper.insert(tUserRole);
        return Result.OK(insert);
    }


    //修改讲师
    @Override
    public Result updateTeacher(UpTeacher upTeacher) {
        TUser tUser1 = this.tUserMapper.selectById(upTeacher.getId());
        QueryWrapper<TUser> queryWrapper=new QueryWrapper<>();
        //判断该讲师是否已存在
        queryWrapper.eq("username",upTeacher.getUsername());
        if (!tUser1.getUsername().equals(upTeacher.getUsername())){
            if(tUserMapper.selectOne(queryWrapper)!=null){
                return Result.ERROR("账号已存在");
            }
        }

        queryWrapper.eq("nickname",upTeacher.getNickname());
        if (!tUser1.getNickname().equals(upTeacher.getNickname())){
            if(tUserMapper.selectOne(queryWrapper)!=null){
                return Result.ERROR("昵称已存在");
            }
        }

        TUser tUser = new TUser();
        tUser.setUserId(upTeacher.getId());
        if (upTeacher.getUsername()!=null&& !upTeacher.getUsername().equals("")){
            tUser.setUsername(upTeacher.getUsername());
        }
        if (upTeacher.getPassword()!=null && !upTeacher.getPassword().equals("")){
            String hashpw = BCrypt.hashpw(upTeacher.getPassword());
            tUser.setPassword(hashpw);
        }
        if (upTeacher.getNickname()!=null && !upTeacher.getNickname().equals("")){
            tUser.setNickname(upTeacher.getNickname());
        }
        if (upTeacher.getPhone()!=null && !upTeacher.getPhone().equals("")){
            tUser.setPhone(upTeacher.getPhone());
        }
        if (upTeacher.getAvatar()!=null && !upTeacher.getAvatar().equals("")){
            tUser.setAvatar(upTeacher.getAvatar());
        }
        if (upTeacher.getSex()!=null){
            tUser.setSex(upTeacher.getSex());
        }
        if (upTeacher.getEmail()!=null  && !upTeacher.getEmail().equals("") ){
            tUser.setEmail(upTeacher.getEmail());
        }
        int i = this.tUserMapper.updateById(tUser);
        return Result.OK(i);
    }

    //根据id找讲师
    @Override
    public Result findOneTeacher(Integer uid) {
        TUser tUser = this.tUserMapper.selectById(uid);
        return Result.OK(tUser);
    }

    //禁用讲师
    @Override
    public Result disableTeacher(Integer uid) {
        TUser tUser = this.tUserMapper.selectById(uid);
        //判断是否已经被禁用，如果已经被禁用就启用
        if (tUser.getState()==0){
            tUser.setState(1);
        }else {
            tUser.setState(0);
        }
        int i = this.tUserMapper.updateById(tUser);
        return Result.OK(i);
    }


    //删除讲师
    @Override
    public Result deleteTeacher(Integer uid) {
        int i = this.tUserMapper.deleteById(uid);
        TUserRole uId = this.tUserRoleMapper.selectOne(new QueryWrapper<TUserRole>().eq("u_id", uid));
        this.tUserRoleMapper.deleteById(uId);
        return Result.OK(i);
    }

    //添加学生
    @Override
    public Result addStudent(StudentAddDto studentAddDto) {
        //判断学生是否重复
        TUser tUser1 = tUserMapper.selectOne(new QueryWrapper<TUser>()
                .eq("username", studentAddDto.getUsername())
                .or()
                .eq("nickname", studentAddDto.getNickname()));
        if (tUser1 != null){
            return Result.ERROR("不能重复添加学生");
        }
        TUser tUser = new TUser();
        tUser.setUsername(studentAddDto.getUsername());
        tUser.setPassword(BCrypt.hashpw("123456"));
        tUser.setAvatar(studentAddDto.getAvatar());
        tUser.setNickname(studentAddDto.getNickname());
        tUser.setPhone(studentAddDto.getPhone());
        tUser.setSex(studentAddDto.getSex());
        tUser.setCreateTime(new Date());
        tUser.setMdId(studentAddDto.getMdId());
        tUser.setClassId(studentAddDto.getClassId());
        tUser.setUpdateTime(new Date());
        tUser.setEmail(studentAddDto.getEmail());
        // 保证随机数为10位数
        Random random = new Random();
        long randomNumber;
        do {
            randomNumber = Math.abs(random.nextLong() % 10000000000L);
        } while (randomNumber < 0);
        String formattedId = String.format("%010d", randomNumber);
        tUser.setStudentId(formattedId);
        this.tUserMapper.insert(tUser);
        //添加角色信息
        TUserRole tUserRole = new TUserRole();
        tUserRole.setUId(tUser.getUserId());
        tUserRole.setRId(3);
        this.tUserRoleMapper.insert(tUserRole);
        return Result.OK();
    }

    @Override
    public Result delBatchStudent(Integer[] ids) {
        this.tUserMapper.deleteBatchIds(Arrays.asList(ids));
        for (Integer id : ids) {
            this.tUserRoleMapper.delete(Wrappers.<TUserRole>lambdaQuery().eq(TUserRole::getUId, id));
        }
        return Result.OKMess("删除成功");
    }

    @Override
    public Result updateStudent(TUser tUser) {
        TUser tUser1 = tUserMapper.selectById(tUser.getUserId());
        tUser.setPassword(tUser1.getPassword());
        tUser.setUsername(tUser.getPhone());
        this.tUserMapper.updateById(tUser);
        return Result.OK();
    }


    //重置密码
    @Override
    public Result resetTeacherPassword(Integer uid) {
        TUser tUser = this.tUserMapper.selectById(uid);
        tUser.setPassword(BCrypt.hashpw("123456"));
        int i = this.tUserMapper.updateById(tUser);
        return Result.OK(i);
    }

    @Override
    public Result allMarket() {
        List<SMarketingdepartment> sMarketingdepartments = sMarketingdepartmentMapper.selectList(null);
        return Result.OK(sMarketingdepartments);
    }

    @Override
    public Result allClass() {
        List<SClass> sClasses = sClassMapper.selectList(null);
        return Result.OK(sClasses);
    }

    @Override
    public void saveRole(TUserRole userRole) {
        tUserRoleMapper.insert(userRole);
    }

    @Override
    public void download(HttpServletResponse response) throws IOException {
        List<StudentVo> list = tUserMapper.selectStudent();
        // 设置响应内容类型为 Excel 文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 对文件名进行编码处理
        String fileName = URLEncoder.encode("学生信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 使用 EasyExcel 将数据写入输出流
        EasyExcel.write(response.getOutputStream(), StudentVo.class).sheet("学生信息").doWrite(list);
    }

    //获取要导出的讲师列表
    @Override
    public List<TeacherExport> getTeacherListExport() {
        List<TUser> list = tUserMapper.getTeacherListExort();
        List<TeacherExport> list1 = new ArrayList<>();
        for (TUser tUser : list){
            TeacherExport teacherExport = new TeacherExport();
            teacherExport.setUserId(tUser.getUserId());
            teacherExport.setUsername(tUser.getUsername());
            teacherExport.setPassword(tUser.getPassword());
            teacherExport.setNickname(tUser.getNickname());
            teacherExport.setPhone(tUser.getPhone());
            teacherExport.setEmail(tUser.getEmail());
            teacherExport.setSex(tUser.getSex());
            teacherExport.setState(tUser.getState());
            teacherExport.setCreateTime(tUser.getCreateTime());
            teacherExport.setUpdateTime(tUser.getUpdateTime());
            list1.add(teacherExport);
        }
        return list1;
    }

    @Override
    public Result disable(UserJinYongDto userJinYongDto) {
        TUser tUser = tUserMapper.selectOne(Wrappers.<TUser>lambdaQuery().eq(TUser::getUserId, userJinYongDto.getUserId()));
        if (tUser.getState() == 0){
            tUser.setState(1);
        }else if (tUser.getState() == 1){
            tUser.setState(0);
        }
        tUserMapper.updateById(tUser);
        return Result.OK();
    }

    @Override
    public Result resetPassword(Integer userId) {
        TUser tUser = tUserMapper.selectById(userId);
        tUser.setPassword(BCrypt.hashpw("123456"));
        tUserMapper.updateById(tUser);
        return Result.OK();
    }

    @Override
    public SMarketingdepartment getMarketAndSex(String s) {
        //针对市场部的名字进行模糊查询
        SMarketingdepartment sMarketingdepartment = sMarketingdepartmentMapper.selectOne(Wrappers.<SMarketingdepartment>lambdaQuery().like(SMarketingdepartment::getName, s));
        return sMarketingdepartment;
    }

    @Override
    public SClass getClassAndSex(String valueOf) {
        //对班级名称进行模糊查询
        SClass sClass = sClassMapper.selectOne(Wrappers.<SClass>lambdaQuery().like(SClass::getClassName, valueOf));
        return sClass;
    }
}